<template>
  <div class="hot-books-page">
     <router-link to="/">
      <el-button type="primary" class="back-home-btn">
        <el-icon><ArrowLeft /></el-icon>
        返回主页
      </el-button>
    </router-link>
    <div class="page-header">
      <h1>热门图书列表</h1>
    </div>
    
    <div v-if="loading" class="loading">加载中...</div>
    <div v-if="error" class="error-message">{{ error }}</div>
    <div v-if="books.length === 0 && !loading && !error" class="no-data">暂无图书数据</div>
    
    <div class="main-content">
      <el-main class="book-grid">
        <el-row :gutter="24">
          <el-col :span="8" v-for="book in books" :key="book.id">
            <el-card class="book-card" @mouseenter="() => setHovered(book.id, true)" @mouseleave="() => setHovered(book.id, false)">

              <div class="cover" 
                :style="{
                  backgroundImage: `url(${book.id ? 'http://localhost:8082/book-covers/' + book.id + '.jpg' : 'https://via.placeholder.com/150x220?text=No+Cover'})`
                }"
                @error="handleImageError(book.id)">
              </div>

              <h3 class="book-title">{{ book.title || '未知' }}</h3>
              <p class="book-author">作者：{{ book.author || '未知作者' }}</p>
              <p class="book-info">分类：{{ book.category || '未知分类' }}</p>
<el-button v-show="hovered.get(book.id)" type="primary" size="small" class="borrow-btn" @click="handleBorrow(book)">立即借阅</el-button>


            </el-card>
          </el-col>
        </el-row>
      </el-main>
    </div>
    
  </div>
  
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { getHotBooks } from '@/services/bookService';
import { addToCart } from '@/services/cartService';
import { ElMessage } from 'element-plus';

const books = ref([]);
const loading = ref(true);
const error = ref(null);
const hovered = ref(new Map());
const setHovered = (id, value) => {
  hovered.value.set(id, value);
};

const handleBorrow = (book) => {
  // 构建完整的封面图片URL并添加到书籍对象
  const bookWithCover = {
    ...book,
    coverUrl: book.id ? `http://localhost:8082/book-covers/${book.id}.jpg` : 'https://via.placeholder.com/150x220?text=No+Cover'
  };
  addToCart(bookWithCover);
  ElMessage.success('已添加到借阅购物车');
};

onMounted(async () => {
  try {
    loading.value = true;
    // 调用bookService中的API方法获取热门图书
    // console.log('调用getHotBooks，参数:', { page: 1, pageSize: 10 });
    const response = await getHotBooks({ page: 1, pageSize: 10 });
    console.log('res', response);  
    // console.log('res.data', response.data.data.data);  
    books.value = response.data?.data.data ? response.data.data.data : [];
  
  } catch (err) {
    error.value = '获取图书数据失败，请稍后重试';
    console.error('API请求错误:', err);
  } finally {
    loading.value = false;
  }
});
</script>

<style scoped>
.hot-books-page {
  min-height: 100vh;
  margin: 0 auto;
  padding: 24px;
  background-color: #f8f9fa;
}



.main-content {
  display: flex;
  gap: 24px;
  max-width: 1200px;
  margin: 0 auto;
}

.book-grid {
  flex: 1;
  margin-bottom: 32px;
}

.book-card {
  height: 320px;
  padding: 16px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.cover {
  height: 180px;
  margin-bottom: 12px;
}

@media (max-width: 768px) {
  .book-card {
    height: auto;
    padding: 12px;
  }
}
.book-card:hover {
  transform: translateY(-4px);
}

.borrow-btn {
  position: absolute;
  bottom: 16px;
  left: 50%;
  transform: translateX(-50%);
  opacity: 0;
  transition: opacity 0.3s ease-in;
}
.book-card:hover .borrow-btn {
  opacity: 1;
}

.cover {
  width: 100%;
  height: 180px;
  background-size: cover;
  background-position: center;
  border-radius: 4px;
  margin-bottom: 12px;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .el-col {
    flex: 0 0 50%; /* 对应span=12，占50%宽度 */
    max-width: 50%;
  }
}
@media (max-width: 768px) {
  .main-content {
  max-width: 1200px;
  margin: 0 auto;
    flex-direction: column;
  }
  .sidebar {
    width: 100% !important;
  }
  .el-col {
    flex: 0 0 100%; /* 对应span=24，占100%宽度 */
    max-width: 100%;
  }
}

.book-title {
  font-size: 16px;
  color: #2c3e50;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.book-author,
.book-info {
  font-size: 14px;
  color: #606266;
  margin-bottom: 4px;
}
</style>